package com.hfjyz.registration.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jxls.transformer.XLSTransformer;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.hfjyz.registration.command.SignUpPersonSearchCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.model.Apply;
import com.hfjyz.registration.model.Depart;
import com.hfjyz.registration.model.Exam;
import com.hfjyz.registration.model.Master;
import com.hfjyz.registration.model.Office;
import com.hfjyz.registration.service.RegistService;
import com.hfjyz.registration.util.MasterUtil;

public class SignupDetailSearchController extends SimpleFormController {

	private RegistService registService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject
	 * (javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		HttpSession session = request.getSession();
		Object cmd = session.getAttribute(getFormSessionAttributeName(request));
		if (cmd != null) {
			return cmd;
		}
		return super.formBackingObject(request);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#
	 * referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors, int)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		SignUpPersonSearchCommand cmd = (SignUpPersonSearchCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(exam);
		Map model = super.referenceData(request, command, errors);
		if (model == null) {
			model = new HashMap();
		}
		initModel(model, cmd);

		return model;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		SignUpPersonSearchCommand cmd = (SignUpPersonSearchCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(ExamContants.SESSION_KEY_EXAM_INFO);
		cmd.setExam(exam);
		request.getSession().setAttribute(getFormSessionAttributeName(), cmd);
		Map model = errors.getModel();
		initModel(model, cmd);
		if (request.getParameter("excelExport") != null) {
			File dest = File.createTempFile("excelExport", ".xlsx");
			dest.deleteOnExit();
			String src = request.getSession().getServletContext()
					.getRealPath("/WEB-INF/template/excelExport.xlsx");
			XLSTransformer transformer = new XLSTransformer();
			transformer.transformXLS(src, model, dest.getAbsolutePath());
			String uuid = UUID.randomUUID().toString();
			request.getSession().setAttribute(uuid, dest.getAbsolutePath());
			model.put("downloadFile", uuid);
		} else {
			model.remove("downloadFile");
		}
		return new ModelAndView(getFormView(), model);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void initModel(Map model,
			SignUpPersonSearchCommand cmd) throws Exception {

		List<Depart> deptList = registService.listDepart(cmd.getExam());

		Depart dept = new Depart();
		dept.setId(-1);
		dept.setName("");
		deptList.add(0, dept);
		model.put("departs", deptList);

		List<Office> officeList = registService.listOffice(cmd.getExam());
		Office office = new Office();
		office.setId(-1);
		office.setName("");
		office.setCode("");
		officeList.add(0, office);
		model.put("offices", officeList);

		List<Master> politicalCodes = MasterUtil.getInstance().getMasters(3);
		Master master = new Master();
		master.setCategory(3);
		master.setCode("-1");
		master.setName("");
		master.setId(-1);
		politicalCodes.add(0, master);
		model.put("politicalCodes", politicalCodes);

		List<Master> identities = MasterUtil.getInstance().getMasters(4);
		Master master2 = new Master();
		master2.setCategory(4);
		master2.setCode("-1");
		master2.setName("");
		master2.setId(-1);
		identities.add(0, master2);
		model.put("identities", identities);

		// if ((cmd.getDeptId() == null || cmd.getDeptId() == -1)
		// && deptList != null && deptList.size() > 0) {
		// cmd.setDeptId(deptList.get(0).getId());
		// }
		// if ((cmd.getPostId() == null || cmd.getPostId() == -1)
		// && officeList != null && officeList.size() > 0) {
		// cmd.setPostId(officeList.get(0).getId());
		// }

		List<Apply> applyList = registService.listApplyUser(cmd);
		model.put("applyUsers", applyList);
	}

	/**
	 * @return the registService
	 */
	public RegistService getRegistService() {
		return registService;
	}

	/**
	 * @param registService
	 *            the registService to set
	 */
	public void setRegistService(RegistService registService) {
		this.registService = registService;
	}

}